package com.itany.jdbc.jdbc;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.itany.jdbc.execption.DataAccessExecption;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author 陈华旺
 * @version 1.0
 * @date 2023年10月25日 16:14
 * @Description 数据库的连接工具
 */
public class JDBCUtil {

    private static DataSource ds;
    private static ThreadLocal<Connection> local;

    static {
        try {
            local = new ThreadLocal<>();
            Properties p = new Properties();
            p.load(JDBCUtil.class.getClassLoader().getResourceAsStream("datasource.properties"));
//            连接池
//            dbcp
//            BasicDataSourceFactory.createDataSource(p);
//            drui
            ds = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("JDBCUtil int error:"+e.getMessage());
        }
    }

    public static Connection getConn() throws SQLException {
        Connection conn = local.get(); // 获取当前业务对应线程的 conn 连接对象
        if(null == conn){
//            当前业务线程没有获取过连接对象
            conn = ds.getConnection();
//            基于当前业务线程，完成存储
            local.set(conn);
        }
        // 当前业务线程已经获取过连接对象
        return conn;
    }
    public static void close(PreparedStatement ps, ResultSet rs){
        if(null != rs) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new DataAccessExecption("databases connection error:" + e.getMessage());
            }
        }
        if(null != ps) {
            try {
                ps.close();
            } catch (SQLException e) {
                throw new DataAccessExecption("databases close error:" + e.getMessage());
            }
        }
    }
    public static void close(){
        Connection conn = local.get();
        if(null != conn){
            local.remove();
            try{
                conn.close();
            } catch (SQLException e){
                throw new DataAccessExecption("数据库连接关闭失败:"+e.getMessage());
            }
        }
    }
}
